<script setup lang='ts'>
  import { nextTick, reactive, ref } from 'vue';
  import { luckDrawApi, propApi } from '@/api/controller';
  import { ToastSuccess, ToastWarning, Toastloading, allNumber } from '@/utils/public';
  import xmImage from '@/components/xmImage/index.vue';
  const dataForm = ref()
  const $emit = defineEmits(['updateList'])
  const action = reactive({
    dialogFormVisible:false,
    disabled:false,
    title:'',
    poolStatus:0,
    computeLoading:false,
    computeNum:0,
    consumeNum:0,
    awardsNum:0,
    profit:0,
    pool_list:[] as Array<poolQuery>,
    options:[] as Array<any>,
    pool_id:0,
  })

  interface poolQuery {
    id:number
    gift_id:number
    gift_name:string
    gift_price:number,
    gift_image:string,
    serachLoading:boolean
    gift_num:number //参与次数
    gift_odds:number | string // 礼物概率
  }
  interface formPoolQuery {
    id:number
    gift_id:number
    gift_num:number
  }
  const handleCompute = async()=>{
    let computeNum = 0; // 参与数量
    let awardsNum = 0; // 礼物池产出
    const { price:cardPrice = 0, need_num=0 } = await wishLuckConfig()
    action.pool_list.forEach((res)=>{
      const {
        gift_num=0, gift_price=0,
      } = res
      computeNum += gift_num
      awardsNum += gift_num * gift_price
    })
    const list = action.pool_list.map(res=>{
      const {
        gift_num=0
      } = res
      return {
        ...res,
        gift_odds: gift_num > 0 ? ((gift_num / computeNum)* 100).toFixed(2) + '%' : '0%'
      }
    })
    action.pool_list = list
    action.computeNum = computeNum
    action.consumeNum = computeNum * (need_num *cardPrice); // 礼物池投入
    action.awardsNum = awardsNum
    action.profit = action.consumeNum - awardsNum; // 礼物池盈利
  }
  const serachGift = async(scoped:any = {})=>{
    const { row={}, $index=-1 } = scoped
    const { gift_id=0 } = row
    if(!gift_id) return ToastWarning('请输入礼物ID后搜索')
    action.pool_list[$index].serachLoading = true
    const res = await propApi.getGifts({
      gift_id
    })
    const { data=[] } = res?.data
    if(data.length > 0) {
      const { price=0, image='', name='' } = data[0]
      const item = action.pool_list[$index]
      action.pool_list[$index] = {
        ...item,
        gift_price:price,
        gift_image:image,
        gift_name:name,
        serachLoading:false
      }
    }else {
      ToastWarning('暂无此礼物ID')
      action.pool_list[$index].serachLoading = false
    }
  }
  interface formQuert {
    pool_id:number
    pool_list:string
  }
  const handleSubmit = async()=>{
    const list = [] as Array<formPoolQuery>
    for(let res of action.pool_list) {
      const { id=0, gift_id=0, gift_num=0, gift_name='', gift_price=''} = res
      if(!id) return ToastWarning('请完善礼物池配置')
      if(gift_id && !gift_name && !gift_price) return ToastWarning(`暂不存在礼物ID：${gift_id}`)
      if(!gift_id) return ToastWarning('请完善礼物池配置')
      list.push({
        id,
        gift_id,
        gift_num
      })
    }
    const loading = Toastloading()
    let form = {
      pool_id:action.pool_id,
      pool_list:JSON.stringify(list)
    } as formQuert
    luckDrawApi.wishLuckSavePoolConfig(form).then(()=>{
      loading.close()
      ToastSuccess('保存礼物池配置成功')
      closeDialog()
    }).catch(()=>{
      loading.close()
    })
  }
  const getPoolList = async()=>{
    const loading = Toastloading()
    const res = await luckDrawApi.wishLuckPoolConfigList({
      pool_id:action.pool_id
    })
    loading.close()
    const { data=[] } = res
    action.pool_list = data
  }
  const wishLuckConfig = async()=> {
    const loading = Toastloading()
    const res = await luckDrawApi.wishLuckConfig()
    loading.close()
    const { data={} } = res || {}
    return data
  }
  const openDialog = async(query:any={})=> {
    const { id, status, options=[], pool_name='' } = query
    action.options = options
    action.poolStatus = status
    action.pool_id = id
    action.title = `礼物池：${pool_name}-礼物池配置`
    await getPoolList()
    action.dialogFormVisible = true
  }
  const closeDialog = ()=>{
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
      top="5vh"
      class="xm-dialog"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :close-on-press-escape="action.disabled"
      width="70%"
      :title="action.title">
      <div class="xm-headTab">
        <div class="labelBox">
          <div class="labelItem">
            <el-button :loading="action.computeLoading" type="primary" @click="handleCompute">计算概率</el-button>
            <el-button :loading="action.computeLoading" type="primary" @click="handleSubmit">保存礼物池配置</el-button>
          </div>
        </div>
        <div class="labelBox input-width">
          <div class="labelItem">
            <div class="label">参与次数：</div>
            <div class="lable-val">{{ action.computeNum }}次</div>
          </div>
          <div class="labelItem">
            <div class="label">礼物池投入：</div>
            <div class="lable-val">{{ action.consumeNum }}钻石</div>
          </div>
          <div class="labelItem">
            <div class="label">礼物池产出：</div>
            <div class="lable-val">{{ action.awardsNum }}钻石</div>
          </div>
          <div class="labelItem">
            <div class="label">盈利：</div>
            <div class="lable-val">{{ action.profit }}钻石</div>
          </div>
          <div class="labelItem">
            <div class="label">礼物池状态：</div>
            <div class="lable-val">
              <el-tag
                :type="['','success','warning'][action.poolStatus] || ''"
              >
                {{ action.options.find(res=>res.type == action.poolStatus)?.label || action.poolStatus }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      <el-table
        class="xm-TableCenter"
        :data="action.pool_list"
        height="500"
        border
      >
        <el-table-column width="80" prop="item_no" label="礼物池ID" />
        <el-table-column width="150" label="礼物ID">
          <template #default="scoped">
            <div class="flex-align">
              <el-input @input="allNumber(scoped.row,'gift_id')" v-model="scoped.row.gift_id" placeholder="礼物ID" />
              <el-button
                :loading="scoped.row.serachLoading"
                text
                type="primary"
                @click="serachGift(scoped)"
                >搜索
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="100" prop="gift_name" label="礼物名称" />
        <el-table-column width="100" prop="gift_price" label="礼物价格" />
        <el-table-column min-width="120" label="礼物图片">
          <template #default="scoped">
            <xmImage style="height: 50px;" :src="scoped.row.gift_image" :list="[scoped.row.gift_image]" />
          </template>
        </el-table-column>
        <el-table-column width="150" label="爆出数量">
          <template #default="scoped">
            <el-input
              @input="allNumber(scoped.row,'gift_num')"
              v-model="scoped.row.gift_num"
              placeholder="请输入爆出数量" />
          </template>
        </el-table-column>
        <el-table-column width="120" prop="gift_odds" label="礼物概率" />
      </el-table>
    </el-dialog>
  </div>
</template>
